package com.jdd.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jdd.common.api.vo.RedisVo;
import com.jdd.common.api.vo.ResultVo;
import com.jdd.common.constant.JddConstant;
import com.jdd.modules.order.entity.ParkOrderInfo;
import com.jdd.modules.parkcar.entity.ParkSpace;
import com.jdd.modules.parking.entity.ParkCarEnterLog;
import com.jdd.modules.parking.entity.ParkCarOutEntranceRecord;
import com.jdd.modules.parking.entity.ParkCarOutLog;
import com.jdd.modules.parking.mapper.ParkCarOutEntranceRecordMapper;
import com.jdd.modules.parking.service.IParkCarOutEntranceRecordService;
import com.jdd.modules.parking.service.IparkCarEnterLogService;
import com.jdd.modules.parking.service.IparkCarOutLogService;
import com.jdd.modules.parking.vo.CarParkingInfoVO;
import com.jdd.modules.sdkidentifyresultpushlog.entity.RestTemplateSpaceVo;
import com.jdd.modules.sdkidentifyresultpushlog.entity.vo.ParkCarEnterLogSyncV3Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;

import javax.annotation.Resource;

/**
 * @version 1.0
 * @Description:
 * @author： jdd尚岳
 * @Date: 2022-03-07 9:01
 */
@Component
@Slf4j
@Async("doSomethingExecutor")
public class AsynRestTmplateUtils {


    public String appScrect;



    public String appId;
    @Resource
    RestTemplateUtils templateUtils;
    @Resource
    IparkCarEnterLogService iparkCarEnterLogService;
    @Resource
    OssUtil ossUtil;
    @Resource
    IparkCarOutLogService iparkCarOutLogService;
    @Resource
    ParkCarOutEntranceRecordMapper parkCarOutEntranceRecordMapper;
    /***
     * @Description  向云端同步入场记录
     * @author shangyue
     * @Date 2022-03-07
     * @param parkCarEnterLog
     * @return
     */

    public void saveParkCarEnterLog(ParkCarEnterLog  parkCarEnterLog){
        log.info("=======开始同步入场记录=====");
        if (StringUtils.isNotBlank(parkCarEnterLog.getOssImgPath())){
            parkCarEnterLog.setImgPath(parkCarEnterLog.getOssImgPath());
         }
        String url = "";
        ResultVo resultVo = assembleRequestFormat(parkCarEnterLog, url);
        log.info("云端保存接口调用结果:{}", resultVo);
        if (JddConstant.SUCCESS_CODE==resultVo.getCode()) {
            parkCarEnterLog.setSynchronousStatus("Y");
        }else {
            parkCarEnterLog.setSynchronousStatus("N");
        }
        iparkCarEnterLogService.updateSynchronousStatus(parkCarEnterLog.getId(),parkCarEnterLog.getSynchronousStatus());

    }
    /***
     * @Description  向云端异步同步出场记录
     * @author shangyue
     * @Date 2022-03-07
     * @param parkCarOutLog
     * @return
     */

    public void saveParkCarOutLog(ParkCarOutLog parkCarOutLog){
        log.info("=======开始异步上传出场记录=====->{}",parkCarOutLog);
        if (StringUtils.isNotBlank(parkCarOutLog.getOssImgPath())){
            parkCarOutLog.setImgPath(parkCarOutLog.getOssImgPath());
        }
        String url = "";;

        ResultVo resultVo = assembleRequestFormat(parkCarOutLog, url);
        log.info("云端保存接口调用结果:{}", resultVo);
         if (JddConstant.SUCCESS_CODE==resultVo.getCode()) {
            parkCarOutLog.setSynchronousStatus("Y");
        }else {
            parkCarOutLog.setSynchronousStatus("N");
        }
        iparkCarOutLogService.updateSynchronousStatus(parkCarOutLog.getId(),parkCarOutLog.getSynchronousStatus());
    }
    /***
     * @Description  计费信息同步到云端
     * @author shangyue
     * @Date 2022-03-07
     * @param parkOrderInfos
     * @return
     */
    public void synchronousParkOrderFee(ParkOrderInfo parkOrderInfos){
           try {
               log.info("计费信息同步云端:-{}", parkOrderInfos);
               String url = "";
               ResponseEntity<ResultVo> post = templateUtils.post(url, parkOrderInfos, ResultVo.class);
               log.info("计费信息同步云端结果:-{}", JSONObject.toJSONString(post));
           }catch (Exception e){
               log.error("计费信息同步失败!");
           }
    }
    /***
     * @Description  月租信息同步云端
     * @author shangyue
     * @Date 2022-03-07
     * @param
     * @return
     */
    public void monthlyCarV3(ParkCarEnterLogSyncV3Vo parkCarEnterLogSyncV3Vo,String url){
        try {
            log.info("月租信息同步云端:-{}", parkCarEnterLogSyncV3Vo);

            if(parkCarEnterLogSyncV3Vo != null && parkCarEnterLogSyncV3Vo.getParkCarEnterLogStr() != null){
                //上传云端 图片路径修改成oss图片路径
                ParkCarEnterLog parkCarEnterLog = JSON.parseObject(parkCarEnterLogSyncV3Vo.getParkCarEnterLogStr(), ParkCarEnterLog.class);
                parkCarEnterLog.setImgPath(parkCarEnterLog.getOssImgPath());
                parkCarEnterLogSyncV3Vo.setParkCarEnterLogStr(JSON.toJSONString(parkCarEnterLog));

                ResultVo resultVo = assembleRequestFormat(parkCarEnterLogSyncV3Vo, url);
                log.info("云端保存接口调用结果:{}", resultVo);
                //如果云端Code返回200(成功)，并且msg不等于"异常:主键冲突记录将不再保存
                if (JddConstant.SUCCESS_CODE==resultVo.getCode()) {
                    parkCarEnterLog.setSynchronousStatus("Y");
                }else {
                    parkCarEnterLog.setSynchronousStatus("N");
                }
                iparkCarEnterLogService.updateSynchronousStatus(parkCarEnterLog.getId(),parkCarEnterLog.getSynchronousStatus());
             }
        }catch (Exception e){
            log.error("月租信息同步云端结果!");
        }
    }


    public void monthlyCarOut(ParkCarEnterLogSyncV3Vo parkCarEnterLogSyncV3Vo,String url){
        try {
            log.info("月租信息同步云端:-{}", parkCarEnterLogSyncV3Vo);

            if(parkCarEnterLogSyncV3Vo != null && parkCarEnterLogSyncV3Vo.getParkCarEnterLogStr() != null){
                //上传云端 图片路径修改成oss图片路径
                ParkCarEnterLog parkCarEnterLog = JSON.parseObject(parkCarEnterLogSyncV3Vo.getParkCarEnterLogStr(), ParkCarEnterLog.class);

                 parkCarEnterLogSyncV3Vo.setParkCarEnterLogStr(JSON.toJSONString(parkCarEnterLog));

                // 请求头设置,x-www-form-urlencoded格式的数据
                ResultVo resultVo = assembleRequestFormat(parkCarEnterLogSyncV3Vo, url);
                log.info("云端保存接口调用结果:{}", resultVo);
                //如果云端Code返回200(成功)，并且msg不等于"异常:主键冲突记录将不再保存
                if (JddConstant.SUCCESS_CODE==resultVo.getCode()) {
                    parkCarEnterLog.setSynchronousStatus("Y");
                }else {
                    parkCarEnterLog.setSynchronousStatus("N");
                }

                iparkCarEnterLogService.updateSynchronousStatus(parkCarEnterLog.getId(),parkCarEnterLog.getSynchronousStatus());
             }
        }catch (Exception e){
            log.error("月租信息同步云端结果!");
        }
    }

    public void redisDelete(String serialNo) {
        try {
            log.info("无牌车出场，删除redis缓存");
            String url = "";
            RedisVo redisVo = new RedisVo();
            redisVo.setSerialNo(serialNo);
            redisVo.setKey("park:cloud:out:fee:");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            //封装参数
            MultiValueMap<String, String> stringStringSortedMap = EncapsulationSignDataUtils.encapsulationParameters(redisVo, appId, appScrect);
            // 组装请求体
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(stringStringSortedMap, headers);
            ResponseEntity<ResultVo> body = templateUtils.post(url, request, ResultVo.class);
             body.getBody();
            log.info("无牌车出场，删除redis缓存结果:{}",body);
        }catch (Exception e){
            log.error("无牌车出场，删除redis缓存出现异常",e.getMessage());
        }


    }

    /***
     * @Description  向云端同步入场记录
     * @author shangyue
     * @Date 2022-03-07
     * @param parkCarEnterLog
     * @return
     */
    public void saveParkCarEnterLogV3(ParkCarEnterLog  parkCarEnterLog){
        log.info("=======开始上传入场记录=====->{}",parkCarEnterLog);


        String url = "";;
        ResultVo resultVo = assembleRequestFormat(parkCarEnterLog, url);
        log.info("云端保存接口调用结果:{}", resultVo);
        //如果云端Code返回200(成功)，并且msg不等于"异常:主键冲突记录将不再保存
        if (JddConstant.SUCCESS_CODE==resultVo.getCode()) {
            parkCarEnterLog.setSynchronousStatus("Y");
        }else {
            parkCarEnterLog.setSynchronousStatus("N");
        }

        iparkCarEnterLogService.updateSynchronousStatus(parkCarEnterLog.getId(),parkCarEnterLog.getSynchronousStatus());

    }

    /**
     * @Description 同步停车记录
     * @author shangyue
     * @Date 2022-06-21
     * @param carParkingInfoVO
     * @return
     */
    public void uploadParkCarOutEntranceRecord(CarParkingInfoVO carParkingInfoVO ) {
        log.info("=======开始同步停车记录=====");
        String url = "";
        ResultVo resultVo = assembleRequestFormat(carParkingInfoVO, url);
        log.info("云端保存接口调用结果:{}", resultVo);
        String synchronousStatus=null;
        //如果云端Code返回200(成功)，并且msg不等于"异常:主键冲突记录将不再保存
        if (resultVo.getCode() == 200) {
            synchronousStatus="Y";
         }else {
            synchronousStatus="N";
        }
        parkCarOutEntranceRecordMapper.updateSynchronousStatus(carParkingInfoVO.getId(),synchronousStatus);
    }
    /**
     * @Description  组装请求头并请求方法
     * @author shangyue
     * @Date 2022-06-21
     * @param body 入参
     * @param url 请求的路径
     * @return
     */

    public ResultVo assembleRequestFormat(Object body,String url){
        // 请求头设置,x-www-form-urlencoded格式的数据
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //封装参数
        MultiValueMap<String, String> stringStringSortedMap = EncapsulationSignDataUtils.encapsulationParameters(body, appId, appScrect);
        // 组装请求体
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(stringStringSortedMap, headers);
        //使用restTemplate远程调用云端保存接口
        ResponseEntity<ResultVo> cmsResultDTO = templateUtils.post(url, request, ResultVo.class);
        //云端返回接口保存结果
        ResultVo resultVo = cmsResultDTO.getBody();
        return resultVo;
    }


    /**
     * @Description
     * @author shangyue
     * @Date 2022-07-07
     * @param fileUrl 文件路径
     * @param ossUrl  阿里云路径
     * @return
     */


    public void uploadOssImg(String fileUrl, String ossUrl) {
        try {
            log.info("=======开始上传OSS图片=====");
            ossUtil.uploadOssImg(fileUrl,ossUrl);
        } catch (Exception e) {
            log.error("图片上传阿里oss失败->{}", e);
        }
        return;
    }
}
